package com.jsdx.td.service;

import com.jsdx.td.common.ApiResponse;
import com.jsdx.td.entity.User;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @作者 TD
 * @日期 2025/3/9
 */
@Service
public class UserService {
    // 模拟数据库
    private static final List<User> users = new ArrayList<>();

    static {
        users.add(new User(1,"颤三","123456",22,"男"));
        users.add(new User(2,"lisi","123456",20,"女"));
    }
    public ApiResponse getUsers(){
        // 查询数据库

        return users == null ? ApiResponse.error("得到失败"):ApiResponse.success(users);
    }

    public ApiResponse getUserById(Integer id) {
      for(User user : users){
          if(user.getId().equals(id)){
              return ApiResponse.success(user);
          }
      }
      return ApiResponse.error("查询失败");
    }

    public ApiResponse addUser(User user) {
        // 添加数据库
        users.add(user);

        return ApiResponse.success("添加成功");
    }

    public ApiResponse updateUser(Integer id, User user) {
        // 更新用户
        for(User u : users){
            if(u.getId().equals(id)){
                u.setName(user.getName());
                u.setAge(user.getAge());
                u.setSex(user.getSex());
                u.setPassword(user.getPassword());
                return ApiResponse.success("更新成功");
            }
        }
        return ApiResponse.success("更新失败，该用户不存在");
    }

    public ApiResponse deleteUser(Integer id) {
//        users.remove()
        // 移除id的用户
        users.removeIf(u -> u.getId().equals(id));
        return ApiResponse.success("去除成功！");
    }
}
